package com.icinfo.cloud.provider.punish.common.datareport.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.TerritoryCodeEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.peripheralinterface.datareport.service.IDataReportService;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CollectReportDataDto;
import com.icinfo.cloud.provider.punish.common.datareport.dto.RevokeDecisionOrCaseInfoDto;
import com.icinfo.cloud.provider.punish.common.datareport.enums.*;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.CaseDataChangeReportRecordMapper;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.CaseDataReportStageInfoMapper;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataChangeReportRecord;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportStageInfo;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataChangeReportRecordService;
import com.icinfo.cloud.provider.punish.common.datareport.service.ICaseDataReportRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @Desc 描述
 * @Author mahan
 * @Date 2023/1/5
 */
@Service
@Slf4j
public class CaseDataChangeReportRecordServiceImpl extends MyBatisServiceSupport implements ICaseDataChangeReportRecordService {

	@Resource
	private CaseMainInfoMapper caseMainInfoMapper;
	@Resource
	private CaseDataChangeReportRecordMapper caseDataChangeReportRecordMapper;
	@Resource
	private CaseDataReportStageInfoMapper caseDataReportStageInfoMapper;
	@Resource
	private ICaseDataReportRecordService caseDataReportRecordService;
	@Resource
	private CaseDataReportDecisionServiceImpl decisionService;
	@Resource
	private IDataReportService dataReportService;


	/**
	 * 保存操作记录表
	 *
	 * @param caseId
	 * @param caseChangeOperationType
	 * @param userId
	 */
	@Override
	public void save(String caseId, String caseChangeOperationType, String userId) {
		//获取案件详情
		CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
		if (caseMainInfo == null) {
			log.error("------------保存案件修改记录，未查询到案件信息，caseId：{}, type：{}, userId：{}-------------", caseId, caseChangeOperationType, userId);
			return;
		}
		//如果是人力社保需要调用新的base上报方法
		try {
			if(TerritoryCodeEnum.RLSB.getCode().equals(caseMainInfo.getCaseTerritoryCode())) {
				CollectReportDataDto dto = new CollectReportDataDto();
				dto.setCaseId(caseMainInfo.getId());
				dto.setCaseTerritoryCode(caseMainInfo.getCaseTerritoryCode());
				//判断是否为多当事人，多当事人处罚告知阶段以后才上报
				//多当事人
				if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())) {
					//处罚告知阶段才上报
					if (Arrays.asList("PUNISH_INFORM", "PUNISH_DECIDE", "PUNISH_EXECUTION", "CLOSE_ARCHIVING").contains(caseMainInfo.getCaseCurrentStageCode())) {
						if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
							dto.setCasePartyType("3");
						} else {
							dto.setCasePartyType("2");
						}
					}
				} else {//单当事人
					dto.setCasePartyType("1");
				}
				//调用接口
				dataReportService.caseDataReport(dto);
			}
		}catch (Exception e){
			e.printStackTrace();
		}

		CaseDataChangeReportRecord caseDataChangeReportRecord = new CaseDataChangeReportRecord();
		caseDataChangeReportRecord.setId(BaseUtil.createUid());
		caseDataChangeReportRecord.setCaseId(caseId);
		caseDataChangeReportRecord.setCaseOperationType(caseChangeOperationType);
		caseDataChangeReportRecord.setCreateUserId(userId);
		caseDataChangeReportRecord.setCaseReportType(CaseChangeOperationTypeEnum.getReportTypeCodeByCode(caseChangeOperationType));
		caseDataChangeReportRecord.setCaseReportStatus(CaseChangeReportStatusEnum.WAIT.getCode());
		caseDataChangeReportRecord.setCreateTime(LocalDateTime.now());
		caseDataChangeReportRecord.setCaseCurrentStageCode(caseMainInfo.getCaseCurrentStageCode());
		caseDataChangeReportRecord.setCaseCurrentLinkCode(caseMainInfo.getCaseCurrentLinkCode());
		caseDataChangeReportRecordMapper.insert(caseDataChangeReportRecord);
	}

	/**
	 * 删除案件之前，需要处理数据上报
	 * 如果大于等于决定阶段，则只需调用撤案接口就行
	 * 如果小于决定阶段，则需上报删除已经成功的所有阶段
	 * @param caseId
	 * @return
	 */
	@Override
	public boolean reportDataBeforeDeleteCase(String caseId){
		//获取上报成功记录
		List<CaseDataReportStageInfo> list = this.getCaseReportStageList(caseId);
		if(list != null && list.size() > 0){
			//获取最后一条记录，判断是否大于等于决定阶段
			CaseDataReportStageInfo stageInfo = list.get(list.size() - 1);
			//如果大于等于决定阶段的排序，则调用撤案接口
			if(stageInfo.getReportStageSort() >= ReportDataTypeEnum.DECISION.getSort()){
				RevokeDecisionOrCaseInfoDto dto = new RevokeDecisionOrCaseInfoDto();
				dto.setCaseId(caseId);
				dto.setRevokeType(ReportRevokeTypeEnum.REVOKE_CASE.getCode());
				dto.setRevokeReason("删除案件");
				Result<String> result = decisionService.revokeDecisionOrCaseInfo(dto);
				return result.getCode() == Constant.INTEGER_200 ? true : false;
			}else {//上报删除每个成功的阶段
				List<String> reportStageList = CollUtil.newArrayList();
				list.forEach(u -> reportStageList.add(u.getReportStageTag()));
				String reportStageIds = CollUtil.join(reportStageList, ",");
				boolean result = caseDataReportRecordService.dataReportSpecialStage(reportStageIds, caseId, CaseDataReportOptTypeEnum.D.getCode());
				return result;
			}
		}
		return true;
	}

	/**
	 * 根据caseId获取当前案件已经上报成功的阶段
	 *
	 * @param caseId
	 * @return
	 */
	private List<CaseDataReportStageInfo> getCaseReportStageList(String caseId) {
		Example example = new Example(CaseDataReportStageInfo.class);
		example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isFinishReport", "1");
		example.orderBy("reportStageSort").asc();
		List<CaseDataReportStageInfo> list = caseDataReportStageInfoMapper.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

}
